/**
 * Created by 功振 on 2016/2/2.
 */
angular.module('Portal').controller('SignInController',
    function ($scope,$rootScope,$state, $cookies, $stateParams, userInfoService,jwtHelper,md5, ADMIN,$base64,SignSwitch) {

    var username = $cookies.get('username');
    if(username !== undefined && username !== null){


        if(SignSwitch.signSwitch){
          $state.go('index');

        }else{
          location.href='/cp';

        }
    }

        $rootScope.$broadcast('MainClassSet', 'reg_bg col-login');

        //at least 3 char
        $scope.checkNullReg = "\S{0,}";

        $scope.ok = function () {
            console.log($scope.form.username.$error.unique)
            if($scope.form.username.$error.unique || ($scope.form.username.$error.unique == undefined && $scope.username != undefined)) {
                $scope.signUpInfo = false;
                $scope.isSignUping = true;
                var userLoginInfo = {
                    username: $scope.username,
                    //email: $scope.email,
                    password: md5.createHash($scope.password),
                }

                if($scope.setPullSecr === true)
                    userLoginInfo['pullSecr'] = $base64.encode($scope.username+':'+$scope.password);

                userInfoService.authenticateUser(userLoginInfo).then(function (response) {

                    var data = jwtHelper.decodeToken(response.data);
                    if (data.authenticated) {
                        //$cookies.put("username", $scope.username);
                        // Temporarily, the following three lines are just for trigger user to complete userinfo.
                        if (!data.hasPhone && ADMIN.ADMIN_USER.indexOf($scope.username) < 0) {
                            window.location.href = "/updatereg";
                        } else {
                           $cookies.put("role", data.role);
                            window.location.href = "/cp";
                            //window.location.reload();
                        }
                        $scope.isUserInfoError = false;
                        console.log("authenticate user succeed");
                    } else {
                        $scope.isUserInfoError = true;
                    }
                }, function (response) {
                    console.log("authenticate user " + userLoginInfo.username + " failed");
                });
            }

        };
    });